package com.jiangnan.warehouse_management.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangnan.warehouse_management.common.exception.BusinessException;
import com.jiangnan.warehouse_management.dto.request.CategoryRequest;
import com.jiangnan.warehouse_management.dto.request.CategoryUpdateRequest;
import com.jiangnan.warehouse_management.dto.response.CategoryQueryResponse;
import com.jiangnan.warehouse_management.dto.response.UserQueryResponse;
import com.jiangnan.warehouse_management.mapper.CategoryMapper;
import com.jiangnan.warehouse_management.pojo.Category;
import com.jiangnan.warehouse_management.pojo.User;
import com.jiangnan.warehouse_management.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.swing.plaf.PanelUI;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private final CategoryMapper categoryMapper;

    @Override
    public CategoryQueryResponse getCategories(Integer page, Integer pageSize, String categoryName) {
        // 参数校验
        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 开启分页，只查询顶层分类
        PageHelper.startPage(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(Category::getParentId);

        if (StringUtils.hasText(categoryName)) {
            queryWrapper.like(Category::getCategoryName, categoryName);
        }
        queryWrapper.orderByDesc(Category::getCreatedAt);

        // 执行查询
        List<Category> topCategories = categoryMapper.selectList(queryWrapper);
        PageInfo<Category> pageInfo = new PageInfo<>(topCategories);

        // 构建树形结构
        List<CategoryQueryResponse.CategoryResponse> categoryResponses = topCategories.stream()
                .map(this::buildCategoryTree)
                .collect(Collectors.toList());

        // 构建返回结果
        CategoryQueryResponse response = new CategoryQueryResponse();
        response.setList(categoryResponses);
        response.setTotal(pageInfo.getTotal());
        response.setPage(page);
        response.setPageSize(pageSize);

        return response;
    }

    // 辅助方法 构建树结构
    private CategoryQueryResponse.CategoryResponse buildCategoryTree(Category category) {
        CategoryQueryResponse.CategoryResponse response = new CategoryQueryResponse.CategoryResponse();
        BeanUtils.copyProperties(category, response);

        // 查询子分类
        LambdaQueryWrapper<Category> childWrapper = new LambdaQueryWrapper<>();
        childWrapper.eq(Category::getParentId, category.getCategoryId());
        List<Category> children = categoryMapper.selectList(childWrapper);

        if (!children.isEmpty()) {
            List<CategoryQueryResponse.CategoryResponse> childrenResponses = children.stream()
                    .map(this::buildCategoryTree)
                    .collect(Collectors.toList());
            response.setChildren(childrenResponses);
        } else {
            response.setChildren(Collections.emptyList());
        }

        return response;
    }

    @Override
    public Category createCategory(CategoryRequest request) {
        Category response = new Category();
        BeanUtils.copyProperties(request, response);
        categoryMapper.insert(response);
        return response;
    }

    @Override
    public CategoryQueryResponse.CategoryResponse getCategoryById(Integer categoryId) {
        // 参数校验
        if (categoryId == null) {
            throw new BusinessException(500, "id为空");
        }

        // 查询分类
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 使用已有的构建树方法
        return buildCategoryTree(category);
    }

    @Override
    @Transactional
    public Category updateCategory(Integer id, CategoryUpdateRequest request) {
        // 查询分类是否存在
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 更新分类信息
        Category updateCategory = new Category();
        updateCategory.setCategoryId(id);
        updateCategory.setCategoryName(request.getCategoryName());
        updateCategory.setDescription(request.getDescription());

        // MyBatis-Plus 会自动更新 updated_at 字段
        int rows = categoryMapper.updateById(updateCategory);
        if (rows != 1) {
            throw new BusinessException(500, "更新分类失败");
        }

        // 返回更新后的完整分类信息
        return categoryMapper.selectById(id);
    }

    @Override
    @Transactional
    public void deleteCategory(Integer id) {
        // 检查分类是否存在
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 检查是否存在子分类
        Long childCount = categoryMapper.selectCount(
                new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, id)
        );

        if (childCount > 0) {
            throw new BusinessException(500, "该分类下存在子分类，无法直接删除");
        }

        // 执行删除操作
        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            throw new BusinessException(500, "删除分类失败");
        }
    }
}
